/**
 * Created by zhaoy on 2016/3/24.
 */

var editor;
var editorId = null;

function initOption(list, index) {
    if(index < list.length){
        var item = list[index];
        var options = item.options;
        if(options == null){
            index = index+1;
            initOption(list,index);
            return ;
        }
        $.post(options.url,{},function(result){
            var optionList = [];
            if(result != null){

                for(var i = 0; i < result.length; i++){
                    var option = {};
                    var record = result[i];
                    var displayField = record[options.displayField];
                    var valueField = record[options.valueField];
                    option.displayField = displayField;
                    option.valueField = valueField;
                    optionList.push(option);
                }
            }
            item.optionList = optionList;
            index = index+1;
            initOption(list,index);
        });
    }
}


Ext.define("Field",{

    getField : function (item) {
        var me = this;
        if(item.type == "text" || item.type == "number" || item.type == "password"){
            return me.getText(item);
        }else if(item.type == "hidden"){
            return me.getHidden(item);
        }else if(item.type == "select"){
            return me.getSelect(item);
        }else if(item.type == "file"){
            return me.getFile(item);
        }else if(item.type == "editor"){
            return me.getEditor(item);
        }else if(item.type == "date"){
            return me.getDateField(item);
        }
    },
    /**
     * 获取普通的输入框
     * @param item
     */
    getText : function (item) {
        var html = "";
        var requireSpan = "";
        var requireEle = "";
        var value = item.value;
        value = value==null?"":value;
        if(item.allowBlank != null && item.allowBlank == false){
            requireSpan = "<span class='text-danger'>*</span>";
            requireEle = " required ";
        }
        html += '<div class="form-group" name="'+item.name+'_div">';
        html += '<label class="col-sm-4 control-label">'+item.text+requireSpan+'</label>';
        html += '<div class="col-sm-8"><input type="'+item.type+'" '+requireEle+ ' class="form-control" name="'+prefix + item.name+'" placeholder="'+item.text+'" value="'+value+'"></div>';
        html += '</div>';
        return html;
    },

    getDateField : function (item) {
        var html = "";
        var requireSpan = "";
        var requireEle = "";
        var value = item.value;
        value = value==null?"":value;
        if(item.allowBlank != null && item.allowBlank == false){
            requireSpan = "<span class='text-danger'>*</span>";
            requireEle = " required ";
        }
        html += '<div class="form-group" name="'+item.name+'_div">';
        html += '<label class="col-sm-4 control-label">'+item.text+requireSpan+'</label>';
        html += '<div class="col-sm-8 input-group date"><span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" '+requireEle+ ' class="form-control" name="'+prefix + item.name+'" placeholder="'+item.text+'" value="'+value+'"></div>';
        html += '</div>';
        return html;
    },

    /**
     * 获取选择框
     * @param item
     */
    getSelect : function (item) {
        var me = this;
        var html = "";
        var value = item.value;
        value = value==null?"":value;
        var optionList = item.optionList;
        var checked;
        var option = "";
        for(var i = 0; i < optionList.length; i++){
            var o = optionList[i];
            var valueField = o.valueField;
            var displayField = o.displayField;
            if(valueField == value){
                checked = "selected";
            }else{
                checked = "";
            }
            option += "<option "+checked+" value='"+valueField+"'>" + displayField + "</option>";
        }
        var requireSpan = '';
        var valid = ' class="form-control   ';
        var multiple = "";
        if(item.allowBlank != null && item.allowBlank == false){
            requireSpan = "<span class='text-danger'>*</span>";
            valid = ' class="form-control required  ';
        }

        if(item.multiple != null && item.multiple == true){
            multiple = "multiple";
            valid += 'chosen-select required';
        }
        valid += ' "';
        html += '<div class="form-group" name="'+item.name+'_div">';
        html += '<label class="col-sm-4 control-label">'+item.text+requireSpan+'</label>';
        html += '<div class="col-sm-8"><select required '+multiple+'  '+valid+'  name="'+prefix + item.name+'" data-placeholder="'+item.text+'">';
        html += option;
        html += '</select></div>';
        html += '</div>';
        return html;
    },

    /**
     * 获取隐藏域
     * @param item
     */
    getHidden : function (item) {
        var html;
        html = '<input type="'+item.type+'" class="form-control '+item.name+'" name="'+prefix + item.name+'" placeholder="'+item.text+'">';
        return html;
    },

    /**
     * 获取文件
     * @param item
     */
    getFile : function (item) {
        var html = "";
        html += '<div class="form-group" name="'+item.name+'_div">';
        html += '<label>'+item.text+'</label>';
        html += '<input type="'+item.type+'" class="form-control"  name="'+prefix + item.name+'" placeholder="'+item.text+'">';
        html += '</div>';
        return html;
    },

    /**
     * 获取编辑器
     * @param item
     */
    getEditor : function (item) {
        var me = this;
        editorId = me.getUUID();
        var html = "";
        var requireSpan = "";
        var requireEle = "";
        var value = item.value;
        value = value==null?"":value;
        if(item.allowBlank != null && item.allowBlank == false){
            requireSpan = "<span class='text-danger'>*</span>";
            requireEle = " required ";
        }
        html += '<div class="form-group" name="'+item.name+'_div">';
        html += '<label class="col-sm-4 control-label">'+item.text+requireSpan+'</label>';
        html += '<div class="col-sm-8"><textarea '+requireEle+' class="form-control" id="'+editorId+'" name="'+prefix + item.name+'"></textarea></div>';
        html += '</div>';
        return html;
    },

    getUUID : function () {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }
});

Ext.define("Pagination",{
    extend : 'Field',
    /**
     * 获取html
     * @returns {string}
     */
    getHtml : function () {
        var me = this;
        var html = '<div id="pagination-modify-form"><form class="form-horizontal" method="post" action="'+crud.update+'" style="padding: 20px;" data-parsley-validate novalidate>';
        if(model != null){
            var profile;
            for(var i = 0 ; i < model.length; i++){
                profile = model[i];
                html += me.getField(profile);
            }
        }
        // html+=' <div class="modal-footer inmodal"><button type="button" id="modalDialogWindow-code001-cancel" class="btn btn-white" data-dismiss="modal">取消</button>';
        // html += '                                            <button type="submit" id="modalDialogWindow-code001-success" class="btn btn-primary">提交</button>' ;
        // html +=  '</div>'
        html += '</form></div>';
        return html;
    },
    /**
     * 获取当前页
     * @returns {*|jQuery}
     */
    getPage : function () {
        var page = $("#pagination-form").find("input[name=page]").attr("value");
        return page;
    },

    /**
     * 获取总页码
     * @returns {*|jQuery}
     */
    getTotalPage : function () {
        var pages = $("#pagination-form").find("input[name=totalPage]").attr("value");
        return pages;
    },
    /**
     * 获取页面的表单元素
     * @returns {*|jQuery|HTMLElement}
     */
    getForm : function () {
        var form = $("#pagination-modify-form form");
        return form;
    },
    /**
     * 获取表单的所有值
     * @returns {{}}
     */
    getValues : function () {
        var me = this;
        var form = me.getForm();
        var inputs = form.find("input");
        var record = {};
        var item;
        for(var i = 0; i < inputs.length; i++){
            item = inputs[i];
            record[prefix + item.name] = $(item).val();
        }
        return record;
    },
    /**
     * 提交表单
     */
    subform : function () {
        var me = this;
        var form = me.getForm();
        form.ajaxSubmit(function (data) {
            location.reload();
        })

    },
    /**
     * 将json数据读取到表单中
     * @param record
     */
    loadRecord : function (record) {
        var me = this;
        if(typeof record == "string"){
            record = JSON.parse(record);
        }
        var form = me.getForm();
        var inputs = form.find("input");
        var selects = form.find("select");
        var textarea = form.find("textarea");
        var item;
        for(var i = 0; i < inputs.length; i++){
            item = inputs[i];
            $(item).attr("value",record[me.getReadName(item.name)]);
        }
        for(var i = 0; i < selects.length; i++){
            item = selects[i];
            var val = record[me.getReadName(item.name)];
            if(val != null && val.indexOf(",") != -1){  //array
                var array = val.split(",");
                for(var i = 0; i < array.length; i++){
                    $(item).find("option[value="+array[i]+"]").attr("selected",true);
                }
            }else{
                $(item).find("option[value="+record[me.getReadName(item.name)]+"]").attr("selected",true);
            }
        }
        reloadChosen();
        for(var i = 0; i < textarea.length; i++){
            item = textarea[i];
            $(item).append(record[me.getReadName(item.name)]);
        }
    },

    /**
     * 获取表单除去前缀的name
     * @param name
     * @returns {*}
     */
    getReadName : function (name) {
        var indexOf = name.indexOf(".");
        if(indexOf > -1){  //存在这个点
            return name.split(".")[1];
        }else{
            return name;
        }
    },
    /**
     * 获取主键
     */
    getPrimaryKey : function () {
        for(var i = 0 ; i < model.length; i++){
            if(model[i].primaryKey){
                return model[i];
            }
        }
    },
    /**
     * 获取选中的checkbox
     * @returns {{set, expr}|*|{}|{ID, NAME, TAG}|{ID, TAG}|jQuery}
     */
    getCheck : function () {
        var checks = $(".i-checks[type=checkbox]:checked");
        return checks;
    },
    /**
     *  获取选中的值
     * @returns {Array}
     */
    getCheckedItems : function () {
        var me = this;
        var list = [];
        var checks = me.getCheck();
        var check;
        for(var i =0; i < checks.length; i++){
            check = checks[i];
            list.push($(check).attr("value"));
        }
        return list;
    },

    showModalDiv : function (title,successFn,closeFn,callback) {
        var me = this;
        // var html = "";
        //  html += ' <div class="modal  fade" id="modalDialogWindow-code001" tabindex="-1" role="dialog"  aria-hidden="true">';
        //  html += '                                <div class="modal-dialog  inmodal">';
        //  html += '                                    <div class="modal-content">';
        //  html += '                                        <div class="modal-header inmodal">';
        //  html += '                                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
        //  html += '                                            <h4 class="modal-title">' +
        //      title +'</h4>';
        //  html += '                                        </div>';
        //  html += '                                        <div class="modal-body">';
        //  html += me.getHtml() +'';
        //  html += '';
        //  html += '                                        </div>';
        //  html += '                                    </div>';
        //  html += '                                </div>';
        //  html += '                            </div>';
        // $("#modal-dialog-content").html(html);

        var windowHeight = document.body.clientHeight - 150;

        var index = layer.open({
            type: 1, //page层
            area: ['500px', windowHeight + 'px'],
            title: title,
            shade: 0, //遮罩透明度
            moveType: 1, //拖拽风格，0是默认，1是传统拖动
            shift: 1, //0-6的动画形式，-1不开启
            maxmin: true, //开启最大化最小化按钮
            content: me.getHtml(),
            btn: ['提交', '关闭'] //只是为了演示
            ,yes: function(){
                var valid = $("#pagination-modify-form form").valid();
                if(valid){
                    $("#pagination-modify-form form").ajaxSubmit(function (response) {
                        if(response!= null){
                            if(response.success == true){
                                layer.msg("成功！");
                                location.reload();
                            }else{
                                layer.msg(response.response);
                            }
                        }
                    })
                }
            }
            ,btn2: function(){
                layer.closeAll();
             }
        });
        // layer.full(index);

        $("#modalDialogWindow-code001-cancel").click(function () {
            layer.closeAll();
        })

        var form = me.getForm();
        form.validate();

        $('.input-group.date').datepicker({
            todayBtn: "linked",
            format : 'yyyy-m-d',
            keyboardNavigation: false,
            forceParse: false,
            language : 'zh-CN',
            calendarWeeks: false,
            autoclose: true
        });

        initChosen();
        
        if(callback != null){
            callback();
        }

        // $("#modalDialogWindow-code001").modal({
        //     show : true,
        //     backdrop : 'static'
        // });
    },
    /**
     * 编辑数据
     * @param id
     */
    editItem : function (id) {
        var me = this;
        var callback = null;
        if(typeof initFormCallback != "undefined"){
            callback = initFormCallback;
        }
        var primaryKey = me.getPrimaryKey();
        var name = primaryKey.name;
        var param = {};
        param[name] = id;
        layer.load();
        $.post(crud.read,param,function(result){
            me.showModalDiv("编辑信息",function () {
                me.subform();
            },null,callback);
            layer.closeAll('loading');
            var detail = result;
            me.loadRecord(detail);
        });
    },
    
    addItem : function () {
      var me = this;
        me.showModalDiv("添加信息",function () {
            me.subform();
        });
    },
    /**
     * 初始化
     */
    init : function () {
        var me = this;

        $(document.body).append("<div id='modal-dialog-content'></div>");
        laypage({
            cont: 'pagination',
            form: 'pagination-form',
            pages: me.getTotalPage(),
            //skin: 'flow', //皮肤
            prev: '<', //若不显示，设置false即可
            next: '>', //若不显示，设置false即可
            curr: function () { //通过url获取当前页，也可以同上（pages）方式获取
                //var page = location.search.match(/page=(\d+)/);
                var page = me.getPage();
                return page ? page : 1;
            }(),
            jump: function (e, first) { //触发分页后的回调
                var attr = this;
                if (!first) { //一定要加此判断，否则初始时会无限刷新
                    var form = attr.form;
                    var page = $("#" + form).find("input[name=page]").attr("value", e.curr);
                    $("#" + form).submit();
                }
            }
        });


        $("#pagination-add").click(function () {
            var callback = null;
            if(typeof initFormCallback != "undefined"){
                callback = initFormCallback;
            }
            me.showModalDiv("添加信息",function () {
                me.subform();
            },null,callback);
        });

        /**
         * 为select添加option
         */

        var selectList = [];
        if(typeof model != "undefined" && model != null){
            var item;
            for(var i = 0 ; i < model.length; i++){
                item = model[i];
                if(item.type == "select"){
                    selectList.push(item);
                }
            }
        }

        /**
         * 使用递归方式设置所有的option
         * @param list
         * @param index
         */
        

        initOption(selectList,0);
        $("#pagination-edit").click(function () {
            var primaryKey = me.getPrimaryKey();
            var name = primaryKey.name;
            var checkedItems = me.getCheckedItems();
            if(checkedItems.length == 1){
                me.editItem(checkedItems[0])
            }else{
                layerAlert("请选择一条数据!");
            }
        });

        $("#pagination-delete").click(function () {
            var checkedItems = me.getCheckedItems();
            if(checkedItems.length > 0){
                layerConfirm('是否删除', {
                    skin: 'layui-layer-molv',
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    var ids = checkedItems.join();
                    var primaryKey = me.getPrimaryKey();
                    var name = primaryKey.name;
                    var param = {};
                    param[name] = ids;
                    $.post(crud.del,param,function(result){
                        layerMsg('删除成功', {icon: 1});
                        location.reload();
                    });
                });
            }else{
                layerAlert("请选择需要删除的数据!");
            }
        });
        
    }
});

var pagination = Ext.create("Pagination");
pagination.init();

$.validator.setDefaults({
    submitHandler: function() {
        var form = pagination.getForm();
        form.ajaxSubmit(function (data) {
            location.reload();
        })
    }
});

$(document).ready(function () {
   $(".table tr").click(function () {
   })



});
function initChosen() {
    var config = {
        '.chosen-select'           : {},
        '.chosen-select-deselect'  : {allow_single_deselect:true},
        '.chosen-select-no-single' : {disable_search_threshold:10},
        '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
        '.chosen-select-width'     : {width:"95%"}
    }
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }
}

function reloadChosen() {
    var callback = null;
    if(typeof initFormCallback != "undefined"){
        initFormCallback();
    }
    $(".chosen-select").trigger("chosen:updated");
}



